from flask import Blueprint, jsonify, request
import os
import json

# 创建蓝图对象
stock_info = Blueprint('stock_info', __name__)

# 股票信息文件路径
STOCK_INFO_FILE = 'data/stock_info.json'

def ensure_data_file():
    """确保数据文件存在，如果不存在则创建一个空的数据文件"""
    os.makedirs(os.path.dirname(STOCK_INFO_FILE), exist_ok=True)
    if not os.path.exists(STOCK_INFO_FILE):
        with open(STOCK_INFO_FILE, 'w', encoding='utf-8') as f:
            json.dump([], f, ensure_ascii=False)

def read_stock_info():
    """读取所有股票信息"""
    ensure_data_file()
    with open(STOCK_INFO_FILE, 'r', encoding='utf-8') as f:
        return json.load(f)

def write_stock_info(data):
    """写入股票信息到文件"""
    ensure_data_file()
    with open(STOCK_INFO_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

@stock_info.route('/stock_info', methods=['GET'])
def get_all_stock_info():
    """获取所有股票信息"""
    try:
        stocks = read_stock_info()
        return jsonify(stocks)
    except Exception as e:
        return jsonify({'error': f'获取股票信息失败: {str(e)}'}), 500

@stock_info.route('/stock_info/<code>', methods=['GET'])
def get_stock_info(code):
    """获取单个股票信息"""
    try:
        stocks = read_stock_info()
        stock = next((s for s in stocks if s['code'] == code), None)
        if stock:
            return jsonify(stock)
        else:
            return jsonify({'error': f'未找到股票代码: {code}'}), 404
    except Exception as e:
        return jsonify({'error': f'获取股票信息失败: {str(e)}'}), 500

@stock_info.route('/stock_info', methods=['POST'])
def add_stock_info():
    """添加新的股票信息"""
    try:
        new_stock = request.json
        if not new_stock or 'code' not in new_stock:
            return jsonify({'error': '股票代码是必需的参数'}), 400
        
        stocks = read_stock_info()
        
        # 检查是否已存在相同代码的股票
        if any(s['code'] == new_stock['code'] for s in stocks):
            return jsonify({'error': f'股票代码已存在: {new_stock["code"]}'}), 409
        
        # 确保必需的字段都存在
        required_fields = ['code', 'name', 'type']
        for field in required_fields:
            if field not in new_stock:
                return jsonify({'error': f'缺少必需的字段: {field}'}), 400
        
        # 设置默认值
        if 'can_trade' not in new_stock:
            new_stock['can_trade'] = "0"
        
        stocks.append(new_stock)
        write_stock_info(stocks)
        
        return jsonify(new_stock), 201
    except Exception as e:
        return jsonify({'error': f'添加股票信息失败: {str(e)}'}), 500

@stock_info.route('/stock_info/<code>', methods=['PUT'])
def update_stock_info(code):
    """更新股票信息"""
    try:
        updated_stock = request.json
        if not updated_stock:
            return jsonify({'error': '请提供要更新的股票信息'}), 400
        
        stocks = read_stock_info()
        
        # 查找要更新的股票
        for i, stock in enumerate(stocks):
            if stock['code'] == code:
                # 更新股票信息，保留原有代码
                updated_stock['code'] = code
                stocks[i] = updated_stock
                write_stock_info(stocks)
                return jsonify(updated_stock)
        
        return jsonify({'error': f'未找到股票代码: {code}'}), 404
    except Exception as e:
        return jsonify({'error': f'更新股票信息失败: {str(e)}'}), 500

@stock_info.route('/stock_info/<code>', methods=['DELETE'])
def delete_stock_info(code):
    """删除股票信息"""
    try:
        stocks = read_stock_info()
        initial_length = len(stocks)
        
        # 过滤掉要删除的股票
        stocks = [s for s in stocks if s['code'] != code]
        
        if len(stocks) < initial_length:
            write_stock_info(stocks)
            return jsonify({'message': f'已删除股票代码: {code}'})
        else:
            return jsonify({'error': f'未找到股票代码: {code}'}), 404
    except Exception as e:
        return jsonify({'error': f'删除股票信息失败: {str(e)}'}), 500

@stock_info.route('/stock_info/init', methods=['POST'])
def initialize_stock_info():
    """初始化股票信息数据"""
    try:
        default_stocks = [
            {"can_trade": "0", "code": "000016.XSHG", "name": "上证50", "type": 1},
            {"can_trade": "0", "code": "000300.XSHG", "name": "沪深300", "type": 1},
            {"can_trade": "0", "code": "000688.XSHG", "name": "科创50", "type": 1},
            {"can_trade": "0", "code": "000819.XSHG", "name": "有色金属", "type": 2},
            {"can_trade": "0", "code": "000852.XSHG", "name": "中证1000", "type": 1},
            {"can_trade": "0", "code": "000903.XSHG", "name": "中证100", "type": 1},
            {"can_trade": "0", "code": "000905.XSHG", "name": "中证500", "type": 1},
            {"can_trade": "0", "code": "399006.XSHE", "name": "创业板指", "type": 1},
            {"can_trade": "0", "code": "399437.XSHE", "name": "证券行业指数", "type": 2},
            {"can_trade": "0", "code": "399673.XSHE", "name": "创业板50", "type": 1},
            {"can_trade": "0", "code": "399913.XSHE", "name": "300医药", "type": 2},
            {"can_trade": "0", "code": "399932.XSHE", "name": "中证消费", "type": 2},
            {"can_trade": "0", "code": "399967.XSHE", "name": "中证军工", "type": 2},
            {"can_trade": "0", "code": "399971.XSHE", "name": "中证传媒", "type": 2},
            {"can_trade": "0", "code": "399976.XSHE", "name": "新能源车", "type": 2},
            {"can_trade": "0", "code": "399987.XSHE", "name": "中证白酒", "type": 2},
            {"can_trade": "0", "code": "399995.XSHE", "name": "中证基建", "type": 2},
            {"can_trade": "1", "code": "513100.XSHG", "name": "纳指etf", "type": 1},
            {"can_trade": "1", "code": "518880.XSHG", "name": "黄金etf", "type": 1}
        ]
        
        write_stock_info(default_stocks)
        return jsonify({'message': '股票信息初始化成功', 'count': len(default_stocks)})
    except Exception as e:
        return jsonify({'error': f'初始化股票信息失败: {str(e)}'}), 500 